package com.ysq.www.api.work.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ysq.www.api.user.entity.User;
import com.ysq.www.api.user.mapper.UserMapper;
import com.ysq.www.api.work.entity.Approve;
import com.ysq.www.api.work.entity.CopyTo;
import com.ysq.www.api.work.entity.Official;
import com.ysq.www.api.work.mapper.ApproveMapper;
import com.ysq.www.api.work.mapper.CopyToMapper;
import com.ysq.www.api.work.mapper.OfficialMapper;
import com.ysq.www.api.work.service.IOfficialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysq.www.common.result.ResultMsg;
import com.ysq.www.common.utils.Comm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 公文表 服务实现类
 * </p>
 *
 * @author dql
 * @since 2020-08-11
 */
@Service
public class OfficialServiceImpl extends ServiceImpl<OfficialMapper, Official> implements IOfficialService {

    @Autowired
    private OfficialMapper officialMapper;

    @Autowired
    private ApproveMapper approveMapper;

    @Autowired
    private CopyToMapper copyToMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 公文拟稿
     * @param official 公文表实体对象
     * @return
     */
    @Override
    @Transactional
    public ResultMsg addOfficial(Official official) {
        official.setCreateTime(Comm.getNow());
        boolean save = this.save(official);
        //创建审批记录
        if (save){
            Approve ap = new Approve();
            ap.setType(3);
            ap.setContentId(official.getId());
            ap.setSupperId(0);
            ap.setLowerId(0);
            ap.setCheckId(official.getApproverId());
            ap.setCheckStatus(0);
            ap.setCreateTime(Comm.getNow());
            ap.setStatus(0);
            approveMapper.insert(ap);

            //抄送记录
            String copyIds = official.getCopyId();
            if (!StringUtils.isEmpty(copyIds)){
                List<CopyTo> cList = new ArrayList<>();
                String[] copyId = copyIds.split(";");
                for (String c : copyId) {
                    CopyTo ct = new CopyTo();
                    ct.setType(2);//公文
                    ct.setContentId(official.getId());//内容id
                    ct.setUserId(Integer.parseInt(c));//抄送至用户的id
                    ct.setCreateTime(Comm.getNow());//创建时间
                    ct.setStatus(0);
                    cList.add(ct);
                }
                if (cList.size() > 0){
                    //copyToMapper.insertList(cList);
                    copyToMapper.insertListByNote(cList);
                }
            }
            return ResultMsg.INSERT_SUCCESS.setNewMsg("提交公文拟稿成功");
        }else return ResultMsg.INSERT_ERROR.setNewMsg("提交失败，内部错误");
    }

    /**
     * 查询我发起的公文拟稿
     * @param userId 发起人用户id
     * @param pageNumber 页码
     * @param pageSize 页大小
     * @param time 日期
     * @return
     */
    @Override
    public IPage<Official> selectSponsorById(Integer userId, Integer pageNumber, Integer pageSize, String time) {
        QueryWrapper<Official> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).eq("user_id",userId);
        if (!StringUtils.isEmpty(time)){
            String startTime = time + " 00:00:00";
            String endTime = time + " 23:59:59";
            wrapper.between("create_time",startTime,endTime);
        }
        wrapper.orderByDesc("create_time");
        Page<Official> page = new Page<>(pageNumber,pageSize);
        return officialMapper.selectPage(page,wrapper);
    }

    /**
     * 查询已发起详情
     * @param oId 公文id
     * @return
     */
    @Override
    public Official selectDetailById(Integer oId) {
        Official off = officialMapper.selectDetailById(oId);
        return getCopyByOfficial(off);
    }


    /**
     * 查询待处理公文拟稿
     * @param userId 用户id（审批者id）
     * @param type 类型：0未处理，1已处理
     * @param pageNumber 页码
     * @param pageSize 页大小
     * @param time 日期
     * @return IPage
     */
    @Override
    public IPage<Official> selectPendingById(Integer userId, Integer type, Integer pageNumber, Integer pageSize, String time) {
        QueryWrapper<Official> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).eq("approver_id",userId);
        if (type == 0) wrapper.eq("check_status",0);
        else if (type == 1){
            wrapper.ne("check_status",0).ne("check_status",3);
            if (!StringUtils.isEmpty(time)){
                String startTime = time + " 00:00:00";
                String endTime = time + " 23:59:59";
                wrapper.between("create_time",startTime,endTime);
            }
        }
        wrapper.orderByDesc("create_time");
        Page<Official> page = new Page<>(pageNumber,pageSize);
        IPage<Official> iPage = officialMapper.selectPage(page, wrapper);
        return iPage;
    }

    /**
     * 查询待处理/已处理详情
     * @param oId 公文id
     * @return Official
     */
    @Override
    public Official selectUntreatedById(Integer oId) {
        Official off = officialMapper.selectDetailById(oId);
        return getCopyByOfficial(off);
    }

    /**
     * 分页查询抄送至我的公文拟稿
     * @param userId 用户id
     * @param pageNumber 页码
     * @param pageSize 页大小
     * @param time 日期
     * @return
     */
    @Override
    public IPage<Official> selectCopyToMeById(Integer userId, Integer pageNumber, Integer pageSize, String time) {
        QueryWrapper<CopyTo> cWrapper = new QueryWrapper<>();
        cWrapper.eq("status",0).eq("user_id",userId).eq("type",2);
        List<CopyTo> cList = copyToMapper.selectList(cWrapper);
        if (cList.isEmpty()) return null;
        List<Integer> idList = new ArrayList<>();
        for (CopyTo c : cList) {
            idList.add(c.getContentId());
        }
        QueryWrapper<Official> oWrapper = new QueryWrapper<>();
        oWrapper.eq("status",0).ne("check_status",3).in("id",idList);
        if (!StringUtils.isEmpty(time)){
            String startTime = time + " 00:00:00";
            String endTime = time + " 23:59:59";
            oWrapper.between("create_time",startTime,endTime);
        }
        oWrapper.orderByDesc("create_time");
        Page<Official> page = new Page<>(pageNumber,pageSize);
        IPage<Official> oPage = officialMapper.selectPage(page, oWrapper);
        return oPage;
    }

    /**
     * 处理公文拟稿
     * @param oId 公文id
     * @param result 处理结果：1通过，2驳回
     * @return
     */
    @Override
    @Transactional
    public ResultMsg disposeOfficialById(Integer oId, Integer result) {
        Official oc = officialMapper.selectById(oId);
        if (oc.getCheckStatus() != 0) return ResultMsg.UPDATE_ERROR.setNewMsg("处理失败,该公文已处理或已撤销");
        oc.setCheckStatus(result);
        oc.setUpdateTime(Comm.getNow());
        this.updateById(oc);
        UpdateWrapper<Approve> wrapper = new UpdateWrapper<>();
        wrapper.set("check_time",Comm.getNow()).set("check_status",result).set("update_time",Comm.getNow()).
                eq("type",3).eq("content_id",oId);
        approveMapper.update(null,wrapper);
        return ResultMsg.SUCCESS.setNewMsg("处理成功");
    }

    /**
     * 撤销公文拟稿
     * @param oId 公文id
     * @return
     */
    @Override
    @Transactional
    public ResultMsg repealOfficialById(Integer oId) {
        Official oc = officialMapper.selectById(oId);
        if (oc.getCheckStatus() != 0) return ResultMsg.UPDATE_ERROR.setNewMsg("撤销失败,该公文已处理或已撤销");
        oc.setCheckStatus(3);
        oc.setUpdateTime(Comm.getNow());
        this.updateById(oc);
        UpdateWrapper<Approve> wrapper = new UpdateWrapper<>();
        wrapper.set("check_time",Comm.getNow()).set("check_status",3).set("update_time",Comm.getNow()).
                eq("type",3).eq("content_id",oId);
        approveMapper.update(null,wrapper);
        return ResultMsg.SUCCESS.setNewMsg("撤销成功");
    }


    /**
     * 公用方法
     * 查询抄送人
     */
    public Official getCopyByOfficial(Official off){
        String copyIds = off.getCopyId();
        if (!StringUtils.isEmpty(copyIds)){//查询是否有抄送人
            List<Integer> idList = new ArrayList<>();
            String[] ids = copyIds.split(";");
            for (String id : ids) {
                idList.add(Integer.parseInt(id));
            }
            QueryWrapper<User> uWrapper = new QueryWrapper<>();
            uWrapper.select("id","real_name","head_url").eq("status",0).in("id",idList);
            List<User> userList = userMapper.selectList(uWrapper);
            off.setCopyList(userList);
        }
      return off;
    }

}
